package 面试.基础题.排序.冒泡排序;

import java.util.Arrays;

/**
 * 冒泡排序
 *
 * @author codex
 * @since 2021-10-01
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] a = {1, 3, 5, 4, 2, 8, 7, 6, 9};
        //bubbleSort1(a);
        //bubbleSort2(a);
        bubbleSort3(a);
    }
    
    /**
     * 基本实现
     *
     * @param a 待排序数组
     */
    public static void bubbleSort1(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(a));
    }
    
    /**
     * 优化1
     *
     * @param a 待排序数组
     */
    public static void bubbleSort2(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < a.length - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    flag = true;
                }
            }
            
            if (!flag) {
                break;
            }
        }
        System.out.println(Arrays.toString(a));
    }
    
    /**
     * 优化2（推荐）
     *
     * @param a 待排序数组
     */
    public static void bubbleSort3(int[] a) {
        int k = a.length - 1;
        while (true) {
            int last = 0;
            for (int j = 0; j < k; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    last = j;
                }
            }
            k = last;
            if (k == 0) {
                break;
            }
        }
        System.out.println(Arrays.toString(a));
    }
    
}
